package com.song.ResourceNode.client;

import java.util.concurrent.TimeUnit;











import com.song.corebean.MessageType;
import com.song.corebean.PackageMessage;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.ReadTimeoutException;
import io.netty.util.concurrent.ScheduledFuture;

public class HeartBeatHandler extends ChannelInboundHandlerAdapter {
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
			throws Exception {
		// TODO Auto-generated method stub
		super.userEventTriggered(ctx, evt);
		
		if( evt instanceof IdleStateEvent)
		{
			IdleStateEvent event = (IdleStateEvent) evt;
			if(event.state()  == IdleState.READER_IDLE)
			{
				System.out.println("---READER_IDLE---");
			}else if(event.state() == IdleState.WRITER_IDLE)
			{
				System.out.println("---WRITER_IDLE---");
			}
			
		}
		
	}

	private volatile ScheduledFuture<?> heartBeat;

	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		
			System.out.println(msg);
	}
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
		
		heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatHandler.HeartBeatTask(ctx), 0, 5000, TimeUnit.MILLISECONDS);
	}




	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {

		System.out.println(cause.getCause());
//		if(cause.getCause() instanceof ReadTimeoutException)
//		{
//			System.out.println("  -ReadTimeoutException- ");
//		}
//		if(heartBeat!=null){
//			heartBeat.cancel(true);
//			heartBeat = null;
//		}
//		ctx.fireExceptionCaught(cause);
	}
	
	private class HeartBeatTask implements Runnable{
		private final ChannelHandlerContext ctx;
		public HeartBeatTask(ChannelHandlerContext ctx){
			this.ctx = ctx;
		}
		
		public void run() {
			// TODO Auto-generated method stub
			PackageMessage message = buildMessage();
			System.out.println(" 客户端发送 心跳信号 :"+message);
			ctx.writeAndFlush(message);
		}
		
		private PackageMessage buildMessage(){
			PackageMessage message = new PackageMessage();
			message.head.messageType=MessageType.HEART_BEAT_REQ;
			return message;
		}
	}
	
}
